package com.example.common.search;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.common.component.GameCtrlCom;
import com.example.common.control.ICallback;
import com.example.common.model.GameApiSearchResp;
import com.example.common.model.GameResp;

import java.util.ArrayList;
import java.util.List;

public class SearchViewModel extends ViewModel {
    public static Integer PN = 1;//页码
    public static Integer LIMIT = 10;//每页显示个数

    private GameCtrlCom gameCtrlCom;

    private List<GameResp> games = new ArrayList<>();//搜索的游戏数据
    private MutableLiveData<Boolean> isLoadDone=new MutableLiveData<>();//加载是否完成
    private MutableLiveData<String> remainMsg = new MutableLiveData<>();//提示消息
    private boolean isEnd=false;

    public SearchViewModel() {
        gameCtrlCom = new GameCtrlCom();
    }

    /**
     * 搜索游戏
     *
     * @param key 搜索关键词
     */
    public void getGameSearch(String key) {
        if(!isEnd){
            isLoadDone.setValue(false);
            gameCtrlCom.getGameSearch(key, PN, LIMIT, new ICallback() {
                @Override
                public void onSuccess(Object response) {
                    GameApiSearchResp resp = (GameApiSearchResp) response;
                    //添加数据
                    games.addAll(resp.getList());
                    //加载完成
                    isLoadDone.setValue(true);
                    //是否还存在后续加载内容
                    if(resp.getNext()==0){
                        isEnd=true;
                    }
                }

                @Override
                public void onFailed(String mes) {
                    isLoadDone.setValue(false);
                    remainMsg.setValue(mes);
                }
            });
            PN++;
        }
    }

    public List<GameResp> getGames() {
        return games;
    }

    public MutableLiveData<Boolean> getIsLoadDone() {
        return isLoadDone;
    }

    public void reSet(){
        PN=1;
        isEnd=false;
        games.clear();
    }
}
